package com.garlic.face.jlf.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Toast;

import com.garlic.face.jlf.R;
import com.garlic.face.jlf.base.BaseActivity;
import com.garlic.face.jlf.transaction.Means;
import com.garlic.face.jlf.transaction.ServiceInterface;
import com.garlic.face.jlf.transaction.balance.LampUtil;
import com.garlic.face.jlf.transaction.balance.ReadSerialPort;
import com.garlic.face.jlf.transaction.balance.SerialPortFunction;
import com.garlic.face.jlf.transaction.constances.JLFConstant;
import com.garlic.face.jlf.utils.LogUtils;
import com.garlic.face.jlf.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;

/**
 * @author wenhui02.liu
 * @date 2018/9/5.
 */

public class ScaleTestActivity extends BaseActivity implements  ReadSerialPort.DataWeight{
    private WeightTipsDialog weightTipsDialog = null;
    private SerialPortFunction serialPortFunction;
    private boolean isVerify = false;
    private static SuperVisorDialog superVisorDialog;
    private boolean blScaleEvent = false; //true-允许触发电子称事件
//    private NormalDialog confirmDlg;
    private CommonDialog mCommonDialog;
    private String superVisor = "";
    private String superVisorPwd = "";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_scale);
        serialPortFunction=SerialPortFunction.getInstance();
        serialPortFunction.setContext(this);

        serialPortFunction.startSerialReadEle(this);
        Means.getInstance().clear();
        Means.InitWeight = Means.weightqty;
        Means.TotalWeight = 0;
        Means.BagWeight = 0;
        Means.blAssistMode = false;
        //绿灯亮
        LampUtil.LampAlarm(serialPortFunction, 1, 1, 0);
        blScaleEvent = true;

        findViewById(R.id.scale_test_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        serialPortFunction.closeEle();
        EventBus.getDefault().unregister(this);
    }

    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 1){
                //弹出重量警告
                if(weightTipsDialog != null && weightTipsDialog.isShowing()){

                }else {
                    weightTipsDialog = new WeightTipsDialog(ScaleTestActivity.this, JLFConstant.WEIGHT_START_VERIFY,"详细重量信息");
                    weightTipsDialog.setCallBack(new WeightTipsDialog.CallBack() {
                        @Override
                        public void adminClick(View view) {
                            showSuperVisor();
                        }

                        @Override
                        public void helpClick(View view) {
                            // 红灯闪烁
                            LampUtil.LampAlarm(serialPortFunction,0, 2, 0);
                        }
                    });

                    weightTipsDialog.show();
                    isVerify = true;
                }
            }
            else if(msg.what == 2){
                //重量正常
                if(weightTipsDialog != null){
                    weightTipsDialog.dismiss();
                    isVerify = false;
                }
            }
        }
    };

    //验证重量，不合法时提示窗口
    private boolean VerifyWeight(double weight)
    {
        //判断秤上是否有未知商品
        if ((weight <=(BigDecimal.valueOf(Means.InitWeight).add(BigDecimal.valueOf(Means.ToleranceNoScan))).doubleValue() && weight > (Means.InitWeight - Means.ToleranceNoScan))
                || (weight == 0) || Means.blAssistMode)
        {
            //误差在30g认为合法，忽略因多拿购物袋可能带来的干扰
            Means.InitWeight = weight;
            Means.TotalWeight = Means.InitWeight;
            Means.BagWeight = 0;
            return true;
        }
        else
        {
            return false;
        }
    }

    private void showSuperVisor(){
        superVisorDialog = SuperVisorDialog.getInstance(getResources().getString(R.string.supervisorTitle),getResources().getString(R.string.supervisorContent), getResources().getString(R.string.supervisorHint));
        superVisorDialog.setCallBack(new SuperVisorDialog.CallBack() {
            @Override
            public void ok_click(View view) {
                if (superVisorDialog.mNumberEdit.length() <= 0) {
                    ToastUtils.toastShow("请输入！", Toast.LENGTH_SHORT);
                } else {
                    if(superVisor.isEmpty()){
                        String number = superVisorDialog.mNumberEdit.getText().toString().trim();
                        superVisorDialog.mNumberEdit.setText("");
                        superVisor = number;
                        //请输入密码
                        superVisorDialog.setMessages(getResources().getString(R.string.superPwdTitle),getResources().getString(R.string.superPwdContent),getResources().getString(R.string.superPwdHint));
                    }
                    else{
                        String pwd = superVisorDialog.mNumberEdit.getText().toString().trim();
                        superVisorPwd = pwd;
                        // 等待 + 禁止扫码
                        showLoad();
                        ServiceInterface.getInstance().superVisor(superVisor,superVisorPwd, JLFConstant.SCO_MANAGEMENT);
                    }
                }
            }

            @Override
            public void delete_click(View view) {
                String temp = superVisorDialog.mNumberEdit.getText().toString().trim();
                if (temp.length() > 1) {
                    superVisorDialog.mNumberEdit.setText(temp.substring(0, temp.length() - 1));
                } else {
                    superVisorDialog.mNumberEdit.setText("");
                }
            }

            @Override
            public void close_click(View view) {
                superVisorDialog.dismiss();
            }
        });
        superVisorDialog.show(getFragmentManager(), "test");
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveResponse(JSONObject jsonObject) {
        try {
            String interfaceType = jsonObject.getString("INTERFACETYPE");
            String retflag = "";
            String retmsg = "";
            if (interfaceType.equals(JLFConstant.TAG_SUPERVISOR_RESPONSE)) {
                hideLoad();
                retflag = jsonObject.getString("retflag");
                retmsg = jsonObject.getString("retmsg");
                if (retflag.equals("0")) {
                    if (isVerify) {
                        superVisorDialog.dismiss();
                        superVisor = "";
                        superVisorPwd = "";
                        /*
                        confirmDlg = NormalDialog.newInstanceTwo("确认重量", "确认装袋台上商品无误吗？");
                        confirmDlg.setCallBackTwo(new NormalDialog.CallBackTwo() {
                            @Override
                            public void twoOk(View view) {
                                confirmDlg.dismiss();
                                Means.InitWeight = Means.weightqty;
                                Means.TotalWeight = Means.InitWeight;
                                Means.BagWeight = 0;
                                Means.blApproveWeight = true;
                            }

                            @Override
                            public void twoCancel(View view) {
                                confirmDlg.dismiss();
                            }
                        });
                        confirmDlg.show(getFragmentManager(), "test");
                        */
                        mCommonDialog = new CommonDialog(ScaleTestActivity.this, "two", "确认重量", "确认装袋台上商品无误吗？");
                        mCommonDialog.setCallBackTwo(new CommonDialog.CallBackTwo() {
                            @Override
                            public void twoOk(View view) {
                                mCommonDialog.dismiss();
                                Means.InitWeight = Means.weightqty;
                                Means.TotalWeight = Means.InitWeight;
                                Means.BagWeight = 0;
                                Means.blApproveWeight = true;
                            }

                            @Override
                            public void twoCancel(View view) {
                                mCommonDialog.dismiss();
                            }
                        });
                        mCommonDialog.show();
                    } else {
                        superVisorDialog.dismiss();
                        superVisor = "";
                        superVisorPwd = "";
                        finish();
                    }
                } else {
                    superVisorPwd = "";
                    ToastUtils.toastShow(retmsg, ToastUtils.ERROR);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 隐藏等待框 + 可扫 + 可称重
     */
    private void hideLoad(){
        blScaleEvent = true;
    }

    /**
     * 显示等待窗 + 不可扫 + 不称重
     */
    private void showLoad(){
        blScaleEvent = false;
    }
    @Override
    public void weight(String weight) {
        if(Means.blAssistMode || !Means.blScaleOK){
            return;
        }
        LogUtils.d("----->weigth" + weight, false);
        LogUtils.d("----->blScaleEvent" + blScaleEvent, false);

        if(blScaleEvent){
            blScaleEvent = false;
            Means.weightqty = Double.parseDouble(weight);
            boolean ret = VerifyWeight(Means.weightqty);
            if(ret){
                blScaleEvent = true;
                Message message = Message.obtain();
                message.what = 2;
                handler.sendMessage(message);
            }
            else{
                blScaleEvent = true;
                Message message= Message.obtain();
                message.what=1;
                handler.sendMessage(message);
            }
        }
    }
}
